<template>
	<view class="address-container">
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<u-loading-icon mode="spinner" size="30"></u-loading-icon>
			<text class="loading-text">正在加载地址...</text>
		</view>
		
		<!-- 错误状态 -->
		<view v-else-if="error" class="error-container">
			<u-empty mode="error" icon="/static/img/error.png">
				<text class="error-text">{{ error }}</text>
				<button class="retry-btn" @click="fetchAddressData">重试</button>
			</u-empty>
		</view>
		
		<!-- 地址列表 -->
		<view class="address-list" v-else-if="addressList.length > 0">
			<view class="address-item" v-for="(item, index) in addressList" :key="item.id" @click="selectAddress(item)">
				<view class="address-content">
					<view class="address-header">
						<text class="contact-name">{{ item.receiverName }}</text>
						<text class="contact-phone">{{ item.receiverPhone }}</text>
						<view class="default-tag" v-if="item.isDefault === 1">默认</view>
					</view>
					<view class="address-detail">{{ item.province }}{{ item.city }}{{ item.district }}{{ item.detailAddress }}</view>
					<view class="address-footer">
						<view class="default-option" v-if="item.isDefault !== 1" @click.stop="setAsDefault(item.id)">
							<view class="radio-btn">
								<view class="radio-inner" :class="{ 'checked': item.isDefault === 1 }"></view>
							</view>
							<text class="radio-text">设为默认</text>
						</view>
						<text class="default-text" v-else>默认地址</text>
						<view class="action-buttons">
							<text class="action-btn edit-btn" @click.stop="editAddress(item)">编辑</text>
							<text class="action-btn delete-btn" @click.stop="deleteAddress(item.id)">删除</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<view class="empty-icon">📍</view>
			<view class="empty-text">暂无收货地址</view>
			<view class="empty-desc">添加收货地址，享受便捷购物</view>
		</view>
		
		<!-- 底部添加按钮 -->
		<view class="bottom-bar">
			<view class="add-btn" @click="addAddress">
				<text class="add-icon">+</text>
				<text class="add-text">添加新收货人</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { getAddressList, deleteAddress as deleteAddressApi, updateAddress } from '@/api/address.js'
	import { getCurrentMemberId, getMemberIdFromAddressList } from '@/utils/userState.js'
	
	export default {
		data() {
			return {
				addressList: [], // 地址列表，从后端获取
				loading: false, // 加载状态
				error: null, // 错误信息
			}
		},
		onLoad() {
			// 监听地址列表刷新事件
			uni.$on('refreshAddressList', this.fetchAddressData);
			
			// 监听请求memberId事件
			uni.$on('requestMemberId', this.handleRequestMemberId);
			
			// 获取地址数据
			this.fetchAddressData();
		},
		onShow() {
			// 页面显示时刷新地址数据
			this.fetchAddressData();
		},
		
		onPullDownRefresh() {
			// 下拉刷新
			this.fetchAddressData().finally(() => {
				uni.stopPullDownRefresh();
			});
		},
		onUnload() {
			// 移除事件监听
			uni.$off('refreshAddressList', this.fetchAddressData);
			uni.$off('requestMemberId', this.handleRequestMemberId);
		},
		computed: {
			// 检查是否有默认地址
			hasDefaultAddress() {
				return this.addressList.some(item => item.isDefault === 1);
			}
		},
		methods: {
			// 处理请求memberId事件
			handleRequestMemberId() {
				// 从地址列表中获取第一个地址的memberId
				if (this.addressList.length > 0) {
					const memberId = this.addressList[0].memberId;
					console.log('响应requestMemberId事件，发送memberId:', memberId);
					uni.$emit('memberIdReceived', memberId);
				} else {
					console.log('地址列表为空，无法获取memberId');
				}
			},
			// 获取地址数据
			async fetchAddressData() {
				this.loading = true;
				this.error = null;
				
				try {
					console.log('开始获取地址数据...');
					
					// 检查用户是否已登录
					const currentMemberId = getCurrentMemberId()
					if (!currentMemberId) {
						this.error = '请先登录'
						this.addressList = []
						return
					}
					
					console.log('当前用户memberId:', currentMemberId)
					console.log('请求URL:', '/address/list');
					
					const response = await getAddressList();
					console.log('API响应:', response);
					
					if (response.code === 200) {
						// 处理返回的数据，确保数据结构一致
						const allAddresses = response.rows.map(item => ({
							id: item.id,
							receiverName: item.receiverName || '收货人',
							receiverPhone: item.receiverPhone || '',
							province: item.province || '',
							city: item.city || '',
							district: item.district || '',
							detailAddress: item.detailAddress || '',
							isDefault: item.isDefault || 0,
							addressAlias: item.addressAlias || '',
							memberId: item.memberId
						}));
						
						// 只显示当前用户的地址数据
						this.addressList = allAddresses.filter(item => item.memberId === currentMemberId)
						console.log('过滤后的地址数据:', this.addressList)
						
						// 确保默认地址的唯一性
						this.ensureDefaultAddress();
					} else {
						this.error = response.msg || '获取地址数据失败';
						console.error('API返回错误:', response);
					}
				} catch (err) {
					console.error('获取地址数据失败:', err);
					if (err.message === '用户未登录') {
						this.error = '请先登录'
					} else {
						this.error = '网络错误，请检查网络连接';
					}
					this.addressList = []
				} finally {
					this.loading = false;
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 选择地址
			selectAddress(address) {
				// 将选中的地址传递回结算页面
				uni.$emit('addressSelected', address);
				uni.navigateBack();
			},
			
			// 添加地址
			addAddress() {
				console.log('跳转到新增地址页面');
				uni.navigateTo({
					url: '/pages/xinzengshouhuodizhi/xinzengshouhuodizhi?mode=add'
				});
			},
			
			// 编辑地址
			editAddress(address) {
				console.log('编辑地址:', address);
				// 将地址数据编码后传递到编辑页面
				const addressData = encodeURIComponent(JSON.stringify(address));
				uni.navigateTo({
					url: `/pages/xinzengshouhuodizhi/xinzengshouhuodizhi?mode=edit&addressData=${addressData}`
				});
			},
			
			// 删除地址
			async deleteAddress(addressId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个地址吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const response = await deleteAddressApi(addressId);
								
								if (response.code === 200) {
									// 从本地数据中移除
									const index = this.addressList.findIndex(item => item.id === addressId);
									if (index !== -1) {
										this.addressList.splice(index, 1);
									}
									
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: response.msg || '删除失败',
										icon: 'none'
									});
								}
							} catch (err) {
								console.error('删除地址失败:', err);
								uni.showToast({
									title: '网络错误，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 设置为默认地址
			async setAsDefault(addressId) {
				try {
					// 先获取当前用户的memberId
					const currentMemberId = getCurrentMemberId();
					if (!currentMemberId) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}
					
					// 通过memberId获取当前用户的地址集合
					const userAddresses = this.addressList.filter(item => item.memberId === currentMemberId);
					if (userAddresses.length === 0) {
						uni.showToast({
							title: '未找到用户地址',
							icon: 'none'
						});
						return;
					}
					
					// 找到要设置为默认的地址对象
					const targetAddress = userAddresses.find(item => item.id === addressId);
					if (!targetAddress) {
						uni.showToast({
							title: '地址不存在',
							icon: 'none'
						});
						return;
					}
					// 在当前用户的地址集合中，将其他地址的isDefault设置为0
					const addressesToUpdate = userAddresses.filter(item => item.id !== addressId && item.isDefault === 1);
			
					const updatePromises = addressesToUpdate.map(item => 
						updateAddress({
							...item,
							isDefault: 0
						})
					);
					// 等待所有更新完成
					await Promise.all(updatePromises);
					
					// 设置目标地址为默认（isDefault为1)
					const response = await updateAddress({
						...targetAddress,
						isDefault: 1
					});
					
					if (response.code === 200) {
						// 更新本地数据：当前用户地址集合中其他地址设为0，目标地址设为1
						userAddresses.forEach(item => {
							if (item.id === addressId) {
								item.isDefault = 1;
							} else {
								item.isDefault = 0;
							}
						});
						
					
						uni.showToast({
							title: '设置成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: response.msg || '设置失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},
			
			// 确保默认地址的唯一性
			ensureDefaultAddress() {
				// 检查是否有多个默认地址，如果有则只保留第一个
				const defaultAddresses = this.addressList.filter(item => item.isDefault === 1);
				if (defaultAddresses.length > 1) {
					// 只保留第一个默认地址，取消其他的默认状态
					let firstDefaultFound = false;
					this.addressList.forEach(item => {
						if (item.isDefault === 1) {
							if (!firstDefaultFound) {
								firstDefaultFound = true;
							} else {
								item.isDefault = 0;
							}
						}
					});
				}
			},
			

		}
	}
</script>

<style scoped>
	.address-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}
	
	/* 加载状态 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
	}
	
	.loading-text {
		font-size: 32rpx;
		color: #999;
		margin-top: 20rpx;
	}
	
	/* 错误状态 */
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
	}
	
	.error-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 10rpx;
	}
	
	.retry-btn {
		width: 200rpx;
		height: 70rpx;
		background-color: #ff4444;
		color: #fff;
		border-radius: 35rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
	
	/* 地址列表 */
	.address-list {
		padding: 20rpx;
	}
	
	.address-item {
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		padding: 30rpx;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.address-item:active {
		background-color: #f8f8f8;
		transform: scale(0.98);
	}
	
	.address-content {
		width: 100%;
	}
	
	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}
	
	.contact-name {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-right: 20rpx;
	}
	
	.contact-phone {
		font-size: 28rpx;
		color: #666;
	}
	
	.default-tag {
		background-color: #ff4444;
		color: #fff;
		font-size: 20rpx;
		padding: 4rpx 12rpx;
		border-radius: 8rpx;
		margin-left: 20rpx;
		border: 1rpx solid #ff4444;
	}
	
	.address-detail {
		font-size: 28rpx;
		color: #666;
		line-height: 1.4;
		margin-bottom: 20rpx;
	}
	
	.address-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 15rpx;
		border-top: 1rpx solid #f0f0f0;
	}
	
	.default-option {
		display: flex;
		align-items: center;
	}
	
	.radio-btn {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10rpx;
	}
	
	.radio-inner {
		width: 16rpx;
		height: 16rpx;
		border-radius: 50%;
		background-color: transparent;
		transition: background-color 0.3s ease;
	}
	
	.radio-inner.checked {
		background-color: #ff4444;
	}
	
	.radio-text {
		font-size: 26rpx;
		color: #666;
	}
	
	.default-text {
		font-size: 26rpx;
		color: #666;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		font-size: 26rpx;
		color: #666;
		cursor: pointer;
	}
	
	.edit-btn {
		color: #007aff;
	}
	
	.delete-btn {
		color: #ff4444;
	}
	
	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
	}
	
	.empty-icon {
		font-size: 120rpx;
		color: #ccc;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 10rpx;
	}
	
	.empty-desc {
		font-size: 24rpx;
		color: #ccc;
	}
	
	/* 底部按钮 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		border-top: 1rpx solid #eee;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
	}
	
	.add-btn {
		width: 100%;
		height: 70rpx;
		background: linear-gradient(135deg, #ff4444, #ff6666);
		color: #fff;
		border-radius: 35rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.add-icon {
		font-size: 32rpx;
		margin-right: 10rpx;
	}
</style> 